package com.bawei.module_home.viewmodel

import androidx.lifecycle.viewModelScope
import com.bawei.library_mvi.model.BaseViewModel
import com.bawei.module_home.intent.FocusIntent
import com.bawei.module_home.model.service.FocusService
import com.bawei.module_home.state.FocusState
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @Author : yaotianxue
 * @Time : On 2023/6/27 10:17
 * @Description : FocusViewModel
 */
class FocusViewModel:BaseViewModel<FocusIntent>() {
    private val service:FocusService by lazy{FocusService()}
    private val _states = MutableStateFlow<FocusState>(FocusState.Init)//MutableStateFlow可变
    val states:StateFlow<FocusState>
        get() = _states
    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is FocusIntent.Focus -> doFocus(it)
                }
            }
        }
    }

    private fun doFocus(it: FocusIntent.Focus) {
        val position = it.position //获得下标
        viewModelScope.launch {
            flow {
                val focus = service.focus(it.focuseUserid, it.focusedUserid)
                emit(focus)

            }.catch { e-> _states.value = FocusState.FocusError(e.message.toString())}
                .collect{
                    val code = it.code
                    if(code == 0){
                        _states.value = FocusState.FocusSuccess(it.data,position)
                    }else{
                        _states.value = FocusState.FocusError(it.msg)
                    }
                }
        }
    }
}